#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QNetworkDatagram>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //创建对象
    socket=new QUdpSocket(this);
    //设置窗口标题
    this->setWindowTitle("服务器");
    //连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,[this](){
            //读取请求并解析
            const QNetworkDatagram& requestDatagram=socket->receiveDatagram();
            QString request=requestDatagram.data();
            //处理响应逻辑
            response=handel(request);
            //回显客户端
            QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
            socket->writeDatagram(responseDatagram);
            //将此次交互信息显示到界面上
            QString log="["+requestDatagram.senderAddress().toString()+
                    ":"+QString::number(requestDatagram.senderPort())+"] req:"
                    +request+", rep:"+response;
            ui->listWidget->addItem(log);
    });
    //绑定端口号
    if(socket->bind(QHostAddress::Any,9090)==false)
    {
        QMessageBox::critical(this,"服务器启动失败",socket->errorString());
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::handel(const QString &request)
{
    return request;
}

